from django.shortcuts import render, redirect, reverse
from web.forms.wiki import WikiAddModelForm
from django.http import JsonResponse
from web import models
from django.views.decorators.csrf import csrf_exempt
from utils.md5 import str_add_uid
from utils.cos import upload_cos_file


def wiki(request, project_id):
    # 判断get 传来的参数,如果有，且合格则传递给前端数据，展示文章详情页
    wiki_id = request.GET.get('wiki_id')
    if not wiki_id or not wiki_id.isdecimal():  # 判断wiki_id 是否存在，或者是否是十进制数字
        return render(request, 'wiki/wiki.html')
    wiki_obj = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
    return render(request, 'wiki/wiki.html', {'wiki_obj': wiki_obj})


# 增加文章
def wiki_add(request, project_id):
    form = WikiAddModelForm(request)
    if request.method == 'POST':
        print(request.POST)
        form = WikiAddModelForm(request, data=request.POST)
        if form.is_valid():
            # 增加文章前 ，需要判断是否选择了父级文章
            if form.instance.parent:
                # 如果存在，则该文章的depth 等于 其父文章的depth+1
                parent_depth = form.instance.parent.depth
                form.instance.depth = parent_depth + 1
            form.instance.project = request.tracer.project
            form.save()
            url = reverse('wiki', kwargs={'project_id': project_id})
            return redirect(url)
        else:
            return render(request, 'wiki/wiki_add.html', {'form': form})
    return render(request, 'wiki/wiki_add.html', {'form': form})


# 显示多级目录

def wiki_catalog(request, project_id):
    # 获取当前项目所有的文章,并发送固定格式的字典给前端,并根据depth排序
    data_list = models.Wiki.objects.filter(project_id=project_id).values('id', 'title', 'parent_id').order_by('depth',
                                                                                                              'id')
    return JsonResponse({'status': True, 'data_list': list(data_list)})


# 删除文档
def wiki_delete(request, project_id, wiki_id):
    wiki_obj = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
    if wiki_obj:
        wiki_obj.delete()
    url = reverse('wiki', kwargs={'project_id': project_id})
    return redirect(url)


# 编辑文档
def wiki_edit(request, project_id, wiki_id):
    """这里使用 add添加的form模板"""
    wiki_obj = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
    form = WikiAddModelForm(request, instance=wiki_obj)
    if request.method == 'POST':
        form = WikiAddModelForm(request, data=request.POST, instance=wiki_obj)
        if form.is_valid():
            if form.instance.parent:
                form.instance.depth = form.instance.parent.depth + 1
            form.instance.project = request.tracer.project
            form.save()
            pre_url = reverse('wiki', kwargs={'project_id': project_id})
            url = "{0}?wiki_id={1}".format(pre_url, wiki_id)
            return redirect(url)
        return render(request, 'wiki/wiki_add.html', {'form': form})
    return render(request, 'wiki/wiki_add.html', {'form': form})


@csrf_exempt  # 免除csrf 认证
def wiki_upload(request, project_id):
    """markdown编辑器 返回前端的格式"""
    result = {
        'success': 0,
        'message': None,
        'url': None
    }
    # print(request.FILES) # 获取上传的内容
    # 获取图片对象
    img_obj = request.FILES.get('editormd-image-file')
    if not img_obj:
        result['message'] = '文件不存在'
    # 获取文件后缀
    ext = img_obj.name.rsplit('.')[-1]
    # 为了防止上传的文件名重复，调用方法，将其初始化唯一
    upload_file_name = '%s.%s' % (str_add_uid(request.tracer.user.mobile_phone), ext)  # 文件名以uuid加手机号的MD5组成
    region = 'ap-shanghai'
    bucket = request.tracer.project.bucket
    img_url = upload_cos_file(region, bucket, img_obj, upload_file_name)
    result['success'] = 1
    result['url'] = img_url
    return JsonResponse(result)
